package com.example.controller;

import com.example.common.Result;
import com.example.domain.dto.MenuDTO;
import com.example.domain.entity.Menu;
import com.example.domain.query.MenuQuery;
import com.example.service.MenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Tag(name = "菜单管理")
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class MenuController {

    private final MenuService menuService;

    @Operation(summary = "获取菜单列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<Menu>> list(MenuQuery query) {
        return Result.success(menuService.getMenuList(query));
    }

    @Operation(summary = "获取菜单树")
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('sys:menu:query')")
    public Result<List<Menu>> getMenuTree() {
        List<Menu> menuTree = menuService.getMenuTree();
        return Result.success(menuTree);
    }

    @Operation(summary = "获取菜单详情")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:query')")
    public Result<Menu> getInfo(@PathVariable Long id) {
        return Result.success(menuService.getMenuById(id));
    }

    @Operation(summary = "新增菜单")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:menu:add')")
    public Result<?> add(@RequestBody @Valid MenuDTO menuDTO) {
        menuService.addMenu(menuDTO);
        return Result.success();
    }

    @Operation(summary = "修改菜单")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result<?> update(@PathVariable Long id, @RequestBody @Valid MenuDTO menuDTO) {
        menuDTO.setId(id);
        menuService.updateMenu(menuDTO);
        return Result.success();
    }

    @Operation(summary = "删除菜单")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result<?> delete(@PathVariable Long id) {
        menuService.deleteMenu(id);
        return Result.success();
    }
} 